
/*
* List of globals
*/

var myListingContainer = new Array();
var friendsListingContainer = new Array();
var listing = {subject: '', description: ''};
var friendsListing = {subject: '', description: '', name:'', id:''};
var mini;
var tabSet;
var message;
var globalFriends = new Array();
var me = {};
var isOwnerViewer = false;

function init() {
  //  clearOutData();
  formatUI();
  onLoadFreinds();
   _IG_AdjustIFrameHeight();
}



function createTab(tabName){
    mini = new gadgets.MiniMessage(); 
    tabSet = new gadgets.TabSet(null, null, document.getElementById("tabContainer"));
    
    var o = tabSet.addTab(tabName+ "'s Listing", { 
                             contentContainer: _gel("yourListinConatiner"),
                             tooltip: "My Tab" 
                        }); 
    var friendsTab = tabSet.addTab("Friends Listing", { 
                             contentContainer: _gel("friendsContainer"),
                             tooltip: "Firends Tab" 
                        }); 
    tabSet.alignTabs('left');
}

function createIframe(){
   
   ifrm = document.createElement("IFRAME");
   ifrm.setAttribute("src", "http://google.com/");
   ifrm.style.width = 640+"px";
   ifrm.style.height = 480+"px";
   document.getElementById("Iframe").appendChild(ifrm);
 
}

function formatUI(){
     //do some cosmetics work
    $('#createNewListing').slideUp();     
    $('#toggle').click(function(){
        $('#createNewListing').slideDown();
    });
    $('#toggle').click(function(){
     	_IG_AdjustIFrameHeight();
     });
    $('#descriptionSubmit').click(function(){
        $('#createNewListing').slideUp();     
    });
    $('#descriptionSubmit').click(function(){
        submitNewListing();
    });
    
    $('#descriptionCancel').click(function(){
       $('#createNewListing').slideUp();  
    });
    
 
}

function onLoadFreinds(){
    //call yourself, your friends and app data to get the data
     var req = opensocial.newDataRequest();
     req.add(req.newFetchPersonRequest("OWNER"), "viewer");
     req.add(req.newFetchPeopleRequest('OWNER_FRIENDS'), 'viewerFriends');
     
    
     var fields = ["Listing"];
     req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "viewer");
     req.add(req.newFetchPersonAppDataRequest("OWNER", fields), "viewer_data");
     req.add(req.newFetchPersonAppDataRequest('OWNER_FRIENDS', fields), 'viewerFriendData');
     req.send(responseOnLoad);
}

/*
*This is for testing purposes only 
*/
function clearOutData(){
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest("OWNER", "Listing", ''));
    req.send(clearNotification);
}

function clearNotification(data){
    if(!data.hadError()){
        alert("Data Cleared");
    }
    console.log(data);
}

//testing code ends
function responseOnLoad(data){
    if(data.hadError()){
        alert("There was a problem communicating with the server, please try again later");
    }else{
                
            //show your name next to the greeting
            var viewer = data.get("viewer").getData();
            me = data.get("viewer").getData();
            console.log("Is Owner the viewer:" +me.isViewer());
            console.log(me);
            createTab(me.getDisplayName());
            isOwnerViewer = me.isViewer();
            console.log("OwnerViewer value" +isOwnerViewer);
            if(!isOwnerViewer){
                document.getElementById('newListingContainer').style.display = 'none';
            }
            var viewerFriends = data.get('viewerFriends').getData();
            var viewerFriendsData = data.get('viewerFriendData').getData();
           /* var name = viewer.getDisplayName();
            document.getElementById('viewer_name').innerHTML = name;
            */
            //show my listings
          //  var x = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
            
            if(typeof(data.get("viewer_data").getData()[viewer.getId()]) != 'undefined'){
                var appData = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
                populateOwnListing(appData);
            }
                             
            //show my friends listing
            populateFriendsListing(viewerFriends, viewerFriendsData);
            
    }
}

function populateFriendsListing(friends, data){
    friends.each(function(person){
        var personData = data[person.getId()];
        if(personData){
            var json = data[person.getId()]['Listing'];
            var frListing = {};
            if(!json){
                frListing ={};
            }
            try {
                frListing = gadgets.json.parse(gadgets.util.unescapeString(json));
              } catch (e) {
                frListing = {};
            }
            globalFriends[person.getId()] = person;
            friendsListingContainer[person.getId()] = frListing;
        }
    });
    
    showFriensListing();  
}

function response(data) {
    if(data.hadError()){
        alert("There was a problem communicating with the server, please try again later");
    }else{
                
            //show your name next to the greeting
            var viewer = data.get("viewer").getData();
           // var viewerFriends = data.get('viewerFriends').getData();
           // var name = viewer.getDisplayName();
           // document.getElementById('viewer_name').innerHTML = name;
            
            //Show my listings
            //get your own app data and display it
            
            var appData = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
            populateOwnListing(appData);
           
     }   
}

function populateOwnListing(appData){
     var unescapedString = gadgets.util.unescapeString(appData); 
     var obj = gadgets.json.parse(unescapedString); 
     myListingContainer.length = 0;
   //  console.log(obj);
     jQuery.each(obj, function(i, val){myListingContainer.push(val)});
     console.log(myListingContainer);
     showListing();
     
      var html = document.getElementById("processingDivContent").innerHTML;
      html += "<br/> Updating UI";
      document.getElementById("processingDivContent").innerHTML = html;
}

function submitNewListing(){
      listing.subject = document.getElementById('subject').value;
      listing.description = document.getElementById('description').value;
      document.getElementById("processingDiv").style.display = "";
      
      var html = "Processing.... <br/> Contacting Google Server";
      document.getElementById("processingDivContent").innerHTML = html;
      
      myListingContainer.push(listing);
      sendData();
      
      postActivity();
    
}

//this is just for updating the viewer's request and listing, call onload friends to update friends listing
function sendData(){
      var req = opensocial.newDataRequest();     
      var json = gadgets.json.stringify(myListingContainer);
      req.add(req.newUpdatePersonAppDataRequest("VIEWER", "Listing", json));
      var fields = ["Listing"];
      req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), "viewer");
      req.add(req.newFetchPersonAppDataRequest("VIEWER", fields), "viewer_data");
      req.add(req.newFetchPeopleRequest('VIEWER_FRIENDS'), 'viewerFriends');
      req.send(response);
}

function showListing(data){
//remove all the existing children for the  tbody
        
        //first remove the existing table body
        var body = document.getElementById('tBody');
        if(body){
            document.getElementById("ownListingTable").removeChild(body);
        }
        var flag = false;
       var tBody = document.createElement("tbody");
        tBody.id = "tBody";
        for(var i=0; i<myListingContainer.length; i++){
            flag = true;
            var tr = document.createElement("tr");
            tr.id = "row_"+i;
            
           jQuery.each(myListingContainer[i], function(i, val){
                var subject = document.createElement("td");
                subject.appendChild(document.createTextNode(val));
                tr.appendChild(subject);
           })            
            
            if(isOwnerViewer){
                var remove = document.createElement("td");
                var link = document.createElement("a");
                link.href = "javascript:void(0);"
                link.id = "removelink_" +i;
                link.innerHTML ="remove";
                remove.appendChild(link);
                tr.appendChild(remove);
            }
            
            tBody.appendChild(tr);    
            document.getElementById("ownListingTable").appendChild(tBody);
        }
        
        setTimeout(function(){
            //hide the message
           document.getElementById("processingDiv").style.display = "none";
           assignHandlers();
        }, 500);
        
        if(!flag){
            document.getElementById('replacingText').innerHTML = "You currently have no listings"; 
            document.getElementById('yourListing').style.display = "none";
        }else{
            document.getElementById('replacingText').innerHTML = " ";
            document.getElementById('yourListing').style.display = "";
            $('#ownListingTable').tableHover(); 
        }
	 _IG_AdjustIFrameHeight();
}


function showFriensListing(){
    var tBody = document.createElement("tbody");
    tBody.id = "firendsTBody";
    var flag = false;
    var count = 0;
  
    for(var key in friendsListingContainer){
        jQuery.each(friendsListingContainer[key], function(i, val){
            flag = true;
            var tr = document.createElement("tr");
            tr.id = "friendsRow_"+i;
            
            var id = document.createElement("td");
            var frnd = document.createElement("a");
            frnd.id = ''+key +"_"+ i+'';
            frnd.name = "Details";
            frnd.href = globalFriends[key].getField(opensocial.Person.Field.THUMBNAIL_URL);
            frnd.setAttribute("class", "jTip")
            
            frnd.innerHTML = globalFriends[key].getDisplayName();
            id.appendChild(frnd);
            
            console.log(globalFriends[key].getField(opensocial.Person.Field.THUMBNAIL_URL));
            tr.appendChild(id);
            
            jQuery.each(val, function(i, x){
                        var subject = document.createElement("td");
                        subject.appendChild(document.createTextNode(x));
                        tr.appendChild(subject);
               }); 
               tBody.appendChild(tr); 
        });   
    }
    
   
    document.getElementById('friendsListingTable').appendChild(tBody);
    
    if(!flag){
        document.getElementById('friendsReplacingText').innerHTML= me.getDisplayName()+ "'s friends currently dont have any listings";
        document.getElementById('firendsListing').style.display= "none";
    }else{
        document.getElementById('friendsReplacingText').innerHTML= "";
        document.getElementById('firendsListing').style.display= " ";
    }
    
     _IG_AdjustIFrameHeight();
}

function createTooltips(tooltipArray){
    console.log(tooltipArray);
    for(var i in tooltipArray){
    console.log(tooltipArray[i]);
   
        if(typeof($('#'+tooltipArray[i])) != "function"){
         console.log($('#'+tooltipArray[i]));
            $('#'+tooltipArray[i]).tooltip({
                track: true, 
                delay: 0, 
                showURL: false, 
                opacity: 1, 
                fixPNG: true, 
                showBody: " - ", 
                extraClass: "pretty fancy", 
                top: -15, 
                left: 5 
            });
        }
    }
}

function assignHandlers(){
    for(var i=0; i<myListingContainer.length; i++){
        $('#removelink_'+i).click(setRemoveLink(i));
    }
}

function setRemoveLink(id){
    return function(){createMessageToRemove(id); }
}

function removeLink(id){
    //get the row id and remove it
    document.getElementById('tBody').removeChild(document.getElementById('row_'+id));
    //remove it from the json object
    myListingContainer.splice(id, 1);
    //make a request and update the UI
    sendData();
    dismissMessage();
}

function createMessageToRemove(id){
    var html = "<p>Are you sure you want to remove the listing? </p> <br/>  <input type='button' value='ok' onclick='removeLink("+id+")' /> <input type='button' value='cancel' onclick='dismissMessage()' />";
     message = mini.createStaticMessage(html);
}

function dismissMessage(){
    mini.dismissMessage(message);    
}

function postActivity(){
      var buysell = document.getElementById('DropDownList1').value;
      
      var title = me.getDisplayName() + " wants to "+buysell+" "+ myListingContainer[myListingContainer.length -1].subject;
      console.log(title);
      var params = {};
      params[opensocial.Activity.Field.TITLE] = title;
      var activity = opensocial.newActivity(params);
      opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
      
      //send message to all your friends saying stuff
      
      var message = opensocial.newMessage(myListingContainer[myListingContainer.length -1].descrption);
      message.setField('TITLE', title);
      
      console.log(message);
      
      //I get Not implemented error
      /*var permission = opensocial.Permission;
      console.log(permission);
      opensocial.requestPermission(permission, "Just like that", shareThisApp)
      opensocial.requestSendMessage('VIEWER_FRIENDS', message, shareThisApp);
      
      opensocial.requestShareApp('VIEWER_FRIENDS', null, shareThisApp)
      */
}

function shareThisApp(data){
    console.log(data);
}
